import type { CodeType } from './../types/user.d'
import { ref, type Ref } from 'vue'

import type { FormInstance } from 'vant'
import { showSuccessToast } from 'vant'
import { sendMobileVerificationCode } from '@/services/user'
import { onUnmounted } from 'vue'

export const useMobileVerificationCode = (mobile: Ref<string>, type: CodeType) => {
  const form = ref<FormInstance | null>(null)
  const time = ref<number>(0)
  let timeID: number | undefined = undefined
  const isHasSend = ref<boolean>(false)

  const send = async () => {
    await form.value?.validate('mobile')
    const code = await sendMobileVerificationCode(mobile.value, type)
    console.log(code)
    showSuccessToast('验证码发送成功！')
    isHasSend.value = true
    // todo： 开启倒计时
    time.value = 60
    timeID = setInterval(() => {
      time.value--
      if (time.value <= 0) {
        window.clearInterval(timeID)
        time.value = 0
        isHasSend.value = false
      }
    }, 1000)
  }

  onUnmounted(() => {
    window.clearInterval(timeID)
  })

  return {
    form,
    send,
    time,
    isHasSend
  }
}
